<template>
  <div class="goc-judge">
    <!-- 加载状态 -->
    <div v-if="isLoading" class="loading-state">
      <div class="loading-spinner"></div>
      <p>正在加载题目...</p>
    </div>

    <!-- 错误状态 -->
    <div v-if="error" class="error-state">
      <p>{{ error }}</p>
      <button @click="loadProblem" class="retry-btn">重试</button>
    </div>

    <!-- 正常状态 -->
    <div v-if="!isLoading && !error">
      <!-- 题目信息 -->
      <div v-if="currentProblem || fullProblemInfo" class="problem-info">
        <h2>{{ (fullProblemInfo || currentProblem).title }}</h2>
        
        <!-- 题目描述 -->
        <div v-if="(fullProblemInfo || currentProblem).description" class="problem-description">
          <h4>题目描述</h4>
          <div v-html="formatContent((fullProblemInfo || currentProblem).description)"></div>
        </div>
        
        <div class="problem-meta">
          <span>难度: {{ (fullProblemInfo || currentProblem).difficultyText || (fullProblemInfo || currentProblem).difficulty }}</span>
          <span>时间限制: {{ (fullProblemInfo || currentProblem).timeLimit }}ms</span>
          <span>内存限制: {{ formatSpaceLimit((fullProblemInfo || currentProblem).spaceLimit) || (fullProblemInfo || currentProblem).memoryLimit }}MB</span>
        </div>
      </div>

      <!-- 编辑器区域 -->
      <div class="editor-section" v-if="currentProblem">
        <div class="editor-layout">
          <!-- 左侧编辑器 -->
          <div class="editor-container">
            <GocEditor
              ref="gocEditor"
              v-model:value="userCode"
              :readOnly="isSubmitting"
              :traceEnabled="true"
              :width="'100%'"
              :height="850"
              @run-start="onRunStart"
              @run-end="onRunEnd"
              @error="onEditorError"
            />
          </div>
        </div>
      </div>

      <!-- 控制按钮 -->
      <div class="judge-controls">
        <button
          class="btn btn-primary"
          @click="runCode"
          :disabled="isSubmitting"
        >
          {{ isSubmitting ? '运行中...' : '运行代码' }}
        </button>
        <button
          class="btn btn-success"
          @click="submitCode"
          :disabled="isSubmitting || !canSubmit"
        >
          {{ isSubmitting ? '提交中...' : '提交代码' }}
        </button>
        <button
          class="btn btn-warning"
          @click="resetCode"
          :disabled="isSubmitting"
        >
          重置代码
        </button>
      </div>
    </div>

    <!-- 判题对比弹窗 -->
    <JudgeComparisonPopup
      :visible="showJudgePopup"
      :userCode="userCode"
      :answerCode="currentAnswerCode"
      :comparisonResults="popupComparisonResults"
      :testCases="testCases || []"
      @close="closeJudgePopup"
      @judge-complete="onJudgeComplete"
    />
  </div>
</template>

<script>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import GocEditor from './GocEditor.vue'
import JudgeComparisonPopup from './JudgeComparisonPopup.vue'
import { fetchQuestionById } from '../api/judge-adapter.js'
import logger from '../utils/logger.js'

export default {
  name: 'GocJudgeSimple',
  components: {
    GocEditor,
    JudgeComparisonPopup
  },
  props: {
    problem: {
      type: Object,
      required: false,
      default: null
    },
    problemId: {
      type: [String, Number, Object],
      required: false,
      default: null
    },
    answerCode: {
      type: String,
      required: false,
      default: null
    },
    fullProblemInfo: {
      type: Object,
      required: false,
      default: null
    }
  },
  emits: ['judge-complete', 'code-submit', 'error', 'problem-loaded'],
  setup(props, { emit }) {
    // 响应式数据
    const gocEditor = ref(null)
    const userCode = ref('')
    const isSubmitting = ref(false)
    const isLoading = ref(false)
    const executionStats = ref({})
    const testCases = ref([])
    const judgeResult = ref(null)
    const currentProblem = ref(null)
    const error = ref('')
    
    // 判题弹窗相关数据
    const showJudgePopup = ref(false)
    const currentAnswerCode = ref('')
    const popupComparisonResults = ref([])

    // 计算属性
    const canSubmit = computed(() => {
      return userCode.value.trim() !== '' && !isSubmitting.value && !isLoading.value
    })

    // 动态加载题目
    const loadProblem = async () => {
      if (!props.problemId) {
        logger.warn('没有提供problemId')
        return
      }

      try {
        isLoading.value = true
        error.value = ''
        logger.log(`正在加载题目 ${props.problemId}...`)
        
        const problemData = await fetchQuestionById(props.problemId)
        currentProblem.value = problemData
        userCode.value = problemData.starterCode || `int main() {
    // 在这里编写你的代码

    return 0;
}`
        
        // 初始化测试用例
        initializeTestCases()
        
        logger.log('题目加载成功:', problemData)
        emit('problem-loaded', problemData)
        
      } catch (err) {
        logger.error('加载题目失败:', err)
        error.value = `加载题目失败: ${err.message}`
        emit('error', err)
      } finally {
        isLoading.value = false
      }
    }

    // 初始化测试数据（改为使用测试数据而不是测试用例）
    const initializeTestCases = () => {
      // 优先使用 fullProblemInfo，然后是 currentProblem，最后是 problemId
      const problemData = props.fullProblemInfo || currentProblem.value || props.problemId
      
      // 移除频繁的日志输出，避免刷屏
      
      if (!problemData) {
        testCases.value = []
        return
      }

      // 🔥 改为从测试数据（testData）获取输入数据
      let testDataArray = null
      
      // 1. 直接检查 testData 字段（数组格式）
      if (problemData.testData && Array.isArray(problemData.testData)) {
        testDataArray = problemData.testData
      }
      // 2. 检查 testDataText 字段（JSON字符串）
      else if (problemData.testDataText || problemData.testData) {
        try {
          const testDataStr = problemData.testDataText || problemData.testData
          if (typeof testDataStr === 'string' && testDataStr.trim()) {
            testDataArray = JSON.parse(testDataStr)
          }
        } catch (error) {
          logger.warn('⚠️ [GocJudge] 解析 testData 失败:', error)
        }
      }

      if (!testDataArray || !Array.isArray(testDataArray)) {
        testCases.value = []
        logger.warn('⚠️ [GocJudge] 未找到测试数据，判题时将无法提供输入')
        return
      }

      // 🔥 将测试数据转换为测试用例格式，content 作为 input
      testCases.value = testDataArray.map((testData, index) => ({
        input: testData.content || '',  // 测试数据的 content 作为输入
        expectedOutput: '',  // 测试数据没有输出，留空
        output: '',  // 测试数据没有输出，留空
        index,
        status: 'pending',
        actualOutput: null,
        error: null,
        executionTime: 0,
        trace: []
      }))
      
      // 只在首次初始化时输出日志
      if (testCases.value.length > 0 && !testCases.value[0].__logged) {
        logger.log('✅ [GocJudge] 测试数据初始化完成，数量:', testCases.value.length)
        logger.log('📝 [GocJudge] 测试数据内容:', testCases.value.map(tc => ({ input: tc.input })))
        testCases.value[0].__logged = true
      }
    }

    // 编辑器事件处理
    const onRunStart = () => {
      logger.log('代码开始运行')
    }

    const onRunEnd = () => {
      logger.log('代码运行结束')
    }

    const onEditorError = (error) => {
      logger.error('编辑器错误', error)
      emit('error', error)
    }



    // 运行代码
    const runCode = async () => {
      if (!gocEditor.value) return

      try {
        isSubmitting.value = true
        await gocEditor.value.run()
        
        // 获取执行统计
        executionStats.value = gocEditor.value.getExecutionStats() || {}
        
      } catch (error) {
        logger.error('运行代码失败:', error)
        emit('error', error)
      } finally {
        isSubmitting.value = false
      }
    }

    // 提交代码进行判题（简化版本：直接显示弹窗）
    const submitCode = async () => {
      logger.log('🚀 submitCode 函数被调用')
      logger.log('📝 userCode.value:', userCode.value)
      
      if (!userCode.value.trim()) {
        logger.log('❌ 用户代码为空，退出')
        return
      }

      try {
        isSubmitting.value = true
        judgeResult.value = null

        logger.log('🔍 直接显示判题弹窗，不运行代码...')
        
        // 获取答案代码
        await getAnswerCode()
        
        // 准备弹窗数据（使用测试用例数据）
        preparePopupDataFromTestCases()

        // 直接显示判题弹窗
        showJudgePopup.value = true

        // 发送代码提交事件（不包含判题结果）
        emit('code-submit', {
          problemId: props.problemId || (currentProblem.value && currentProblem.value.id),
          code: userCode.value,
          result: null
        })

        logger.log('✅ 判题弹窗已显示')

      } catch (error) {
        logger.error('显示判题弹窗失败:', error)
        emit('error', error)
      } finally {
        isSubmitting.value = false
      }
    }

    // 获取答案代码
    const getAnswerCode = async () => {
      try {
        const problemData = currentProblem.value || props.problem
        let answerCode = problemData?.expectedCode || props.answerCode
        
        // 如果没有答案代码或者是模板代码，尝试从API获取
        if (!answerCode || answerCode.includes('通用的模板') || answerCode.includes('在这里编写你的代码')) {
          logger.log('🔍 尝试从API获取答案代码...')
          try {
            const { getTestCode } = await import('@/api/testQuestion.js')
            const questionId = props.problemId || (problemData && problemData.id)
            if (questionId) {
              const response = await getTestCode(questionId)
              if (response && response.data) {
                if (response.data.code === 0 && response.data.data) {
                  answerCode = response.data.data
                } else if (typeof response.data === 'string') {
                  answerCode = response.data
                }
                logger.log('✅ 从API获取到答案代码:', answerCode)
              }
            }
          } catch (apiError) {
            logger.warn('⚠️ API获取答案代码失败:', apiError.message)
          }
        }
        
        currentAnswerCode.value = answerCode || ''
        logger.log('📝 最终答案代码:', currentAnswerCode.value)
      } catch (error) {
        logger.error('❌ 获取答案代码失败:', error)
        currentAnswerCode.value = ''
      }
    }

    // 准备弹窗数据（使用测试数据）
    const preparePopupDataFromTestCases = () => {
      // 🔥 从测试数据中提取数据（现在使用测试数据而不是测试用例）
      const testCaseData = (testCases.value && Array.isArray(testCases.value) && testCases.value.length > 0) ? testCases.value[0] : null
      
      if (testCaseData) {
        // 设置输入输出数据
        popupComparisonResults.value = [{
          index: 1,
          score: 0, // 初始分数为0，等待执行后更新
          details: '等待执行'
        }]
        
        logger.log('📋 准备弹窗数据，测试数据:', testCaseData)
      } else {
        // 如果没有测试数据，创建默认数据
        popupComparisonResults.value = [{
          index: 1,
          score: 0,
          details: '无测试数据'
        }]
        logger.warn('⚠️ 没有找到测试数据')
      }
    }

    // 关闭判题弹窗
    const closeJudgePopup = () => {
      showJudgePopup.value = false
    }

    // 🔥 处理判题完成事件（接收来自 JudgeComparisonPopup 的判题结果）
    const onJudgeComplete = (result) => {
      logger.log('✅ [GocJudge] 收到判题完成事件:', result)
      logger.log('📊 [GocJudge] 得分:', result.score)
      logger.log('📊 [GocJudge] 相似度:', result.similar)
      logger.log('📊 [GocJudge] 题目信息:', currentProblem.value)
      
      // 🔥 将判题结果转发给父组件（HomeworkDetail）
      // 传递完整的题目信息，确保父组件能正确识别题目ID
      emit('judge-complete', result, currentProblem.value || props.problem)
      
      logger.log('✅ [GocJudge] 已转发 judge-complete 事件给父组件')
    }

    // 重置代码
    const resetCode = () => {
      const problemData = currentProblem.value || props.problem
      if (problemData) {
        userCode.value = problemData.starterCode || ''
      }
      judgeResult.value = null
      if (testCases.value && Array.isArray(testCases.value)) {
        testCases.value.forEach(testCase => {
          testCase.status = 'pending'
          testCase.actualOutput = null
          testCase.error = null
          testCase.executionTime = 0
          testCase.trace = []
        })
      }
    }

    // 监听problemId变化
    watch(() => props.problemId, (newId) => {
      if (newId) {
        loadProblem()
      }
    })

    // 监听fullProblemInfo变化
    watch(() => props.fullProblemInfo, (newFullProblemInfo, oldFullProblemInfo) => {
      if (newFullProblemInfo) {
        // 移除日志，避免频繁触发时刷屏
        
        currentProblem.value = newFullProblemInfo
        
        // 🔥 只在首次加载或用户代码为默认模板时才设置初始代码
        // 避免覆盖用户已经写入的代码
        const isDefaultCode = !userCode.value || 
                            userCode.value.includes('// 在这里编写你的代码') ||
                            userCode.value.trim() === '' ||
                            !oldFullProblemInfo  // 首次加载
        
        if (isDefaultCode) {
          userCode.value = newFullProblemInfo.starterCode || newFullProblemInfo.initialCode || `int main() {
    // 在这里编写你的代码

    return 0;
}`
        }
        
        initializeTestCases()
      }
    })

    // 监听problem变化
    watch(() => props.problem, (newProblem, oldProblem) => {
      if (newProblem) {
        // 移除日志，避免频繁触发时刷屏
        
        currentProblem.value = newProblem
        
        // 🔥 只在首次加载或用户代码为默认模板时才设置初始代码
        // 避免覆盖用户已经写入的代码
        const isDefaultCode = !userCode.value || 
                            userCode.value.includes('// 在这里编写你的代码') ||
                            userCode.value.trim() === '' ||
                            !oldProblem  // 首次加载
        
        if (isDefaultCode) {
          userCode.value = newProblem.starterCode || newProblem.initialCode || `int main() {
    // 在这里编写你的代码

    return 0;
}`
        }
        
        initializeTestCases()
      }
    })

    // 格式化内容（将换行符转换为HTML）
    const formatContent = (content) => {
      if (!content) return ''
      return content.replace(/\n/g, '<br>')
    }

    // 格式化空间限制
    const formatSpaceLimit = (spaceLimitBytes) => {
      if (!spaceLimitBytes) return ''
      
      const bytes = Number(spaceLimitBytes)
      if (bytes >= 1048576) { // >= 1MB
        return `${(bytes / 1048576).toFixed(1)}MB`
      } else if (bytes >= 1024) { // >= 1KB
        return `${(bytes / 1024).toFixed(1)}KB`
      } else {
        return `${bytes}字节`
      }
    }

    // 生命周期
    onMounted(() => {
      logger.log('🚀 [GocJudge] 组件开始挂载...')
      // 如果有problemId，则动态加载题目
      if (props.problemId) {
        loadProblem()
      } else if (props.fullProblemInfo) {
        // 如果传入了完整的题目信息，则使用它
        logger.log('📦 [GocJudge] 使用 fullProblemInfo:', props.fullProblemInfo)
        currentProblem.value = props.fullProblemInfo
        userCode.value = props.fullProblemInfo.starterCode || `int main() {
    // 在这里编写你的代码

    return 0;
}`
        initializeTestCases()
      } else if (props.problem) {
        // 如果直接传入了problem对象，则使用它
        currentProblem.value = props.problem
        userCode.value = props.problem.starterCode || `int main() {
    // 在这里编写你的代码

    return 0;
}`
        initializeTestCases()
      }
      logger.log('✅ [GocJudge] 组件挂载完成')
    })

    onUnmounted(() => {
      logger.log('🧹 [GocJudge] 开始清理组件资源...')
      
      try {
        // 停止编辑器运行
        if (gocEditor.value) {
          try {
            gocEditor.value.stop()
            logger.log('✅ [GocJudge] 编辑器停止完成')
          } catch (error) {
            logger.warn('⚠️ [GocJudge] 停止编辑器时出错:', error)
          }
        }
        
        // 清理状态
        isSubmitting.value = false
        isLoading.value = false
        executionStats.value = {}
        judgeResult.value = null
        error.value = null
        
        logger.log('✅ [GocJudge] 组件资源清理完成')
      } catch (error) {
        logger.error('❌ [GocJudge] 清理过程中发生错误', error)
      }
    })

    return {
      gocEditor,
      userCode,
      isSubmitting,
      isLoading,
      executionStats,
      testCases,
      judgeResult,
      currentProblem,
      error,
      canSubmit,
      showJudgePopup,
      currentAnswerCode,
      popupComparisonResults,
      onRunStart,
      onRunEnd,
      onEditorError,
      runCode,
      submitCode,
      resetCode,
      loadProblem,
      getAnswerCode,
      preparePopupDataFromTestCases,
      closeJudgePopup,
      onJudgeComplete,
      formatContent,
      formatSpaceLimit
    }
  }
}
</script>

<style scoped>
.goc-judge {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  font-family: Arial, sans-serif;
}

.editor-layout {
  display: flex;
  gap: 20px;
}

.editor-container {
  flex: 1;
  min-width: 0;
}

/* 判题控制按钮样式 */
.judge-controls {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
}

.btn {
  padding: 12px 24px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  font-weight: bold;
  transition: background-color 0.2s;
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.btn-primary {
  background: #007bff;
  color: white;
}

.btn-primary:hover:not(:disabled) {
  background: #0056b3;
}

.btn-success {
  background: #28a745;
  color: white;
}

.btn-success:hover:not(:disabled) {
  background: #1e7e34;
}

.btn-warning {
  background: #ffc107;
  color: #212529;
}

.btn-warning:hover:not(:disabled) {
  background: #e0a800;
}

/* 加载状态样式 */
.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px;
  color: #666;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #3498db;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 20px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 错误状态样式 */
.error-state {
  text-align: center;
  padding: 40px;
  color: #e74c3c;
}

.retry-btn {
  margin-top: 20px;
  padding: 10px 20px;
  background: #3498db;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

/* 题目信息样式 */
.problem-info {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.problem-info h2 {
  margin: 0 0 10px 0;
  color: #2c3e50;
  font-size: 24px;
}

.problem-meta {
  display: flex;
  gap: 20px;
  margin-top: 10px;
  font-size: 16px;
  color: #666;
}

/* 题目描述相关样式 */
.problem-description {
  margin: 15px 0;
  padding: 15px;
  background: white;
  border-radius: 6px;
  border-left: 4px solid #3498db;
}

.problem-description h4 {
  margin: 0 0 10px 0;
  color: #2c3e50;
  font-size: 16px;
  font-weight: bold;
}

.problem-description div {
  color: #555;
  line-height: 1.6;
}
</style>
